<?php


namespace app\admin\controller\card;

use app\common\controller\Backend;
use app\common\model\card\Kabawlogtype;
use think\Db;

/**
 * 划拨与记录
 *
 * @icon fa fa-circle-o
 */
class Appropriate extends Backend
{

    /**
     * Transferlog模型对象
     * @var \app\common\model\card\entity\Transferlog
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\card\Entity;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 查看
     */
    public function index()
    {
        $this->loadlang('entity');
        $this->loadlang('card/transferlog');
        return $this->view->fetch();
    }

    /**
     * 实体卡记录
     * */
    public function entity()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['entitysite'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $logtype=Kabawlogtype::field("card_type_name,number,price")
                    ->where(["card_kabaw_id"=>$row["entitysite"]["card_kabaw_id"],"card_kabaw_entity_id"=>$row["id"]])
                    ->select();
                $logtype_str="";
                if(!empty($logtype)){
                    foreach ($logtype as $k=>$vs){
                        if(empty($k)){
                            $logtype_str="<p>".$vs["card_type_name"]."(".$vs["number"]."次)</p>";
                        }else{
                            $logtype_str.="<p>".$vs["card_type_name"]."(".$vs["number"]."次)</p>";
                        }
                    }
                }
                $row["logtype"]=$logtype_str;
                $row["residue"]=$row["number"]-$row["transfer_num"];
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch("index");
    }
    /**
     * 划拨
     * */
    public function transfer(){
        if (!$this->request->param("id")) $this->error('id为空');
        $ids=$this->request->param("id");
        $row = $this->model->get($ids);
        //if($row["status"]!=1) $this->error("请先印刷");
        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $row= $this->model->get($ids);
                $Entitylog=new \app\common\model\card\Entitylog();
                $exchange_num=$Entitylog->where(["card_entity_id"=>$row["id"],"transfer_data"=>'0','status'=>'1'])->count();
                $num=$row["transfer_num"]+$params["transfer_num"];//+$exchange_num;
                if (empty($params["lifespan"])) $this->error('请选择有效时间');
                $lifespan=explode(" - ",$params["lifespan"]);
                if($row["number"]<($num+$exchange_num)) $this->error("数量不足，最多划拨".($row["number"]-$row["transfer_num"]-$exchange_num));
                Db::startTrans();
                try {
                    $data=[
                        "transfer_num"=>$row["transfer_num"]+$params["transfer_num"],
                        "transfer_time"=>time(),
                    ];
                    $row->allowField(true)->save($data);
                    /********* 修改实体卡记录表 start******************/
                    $log_update=[];
                    $log_list=$Entitylog->where(["card_entity_id"=>$row["id"]])//,'status'=>'0'
                        ->whereIn("transfer_data",['0','3'])
                        ->limit($params["transfer_num"])
                        ->order("id","asc")
                        ->select();
                    foreach ($log_list as $k=>$v){
                        $log_update[$k]=[
                            "id"=>$v["id"],
                            "transfer_data"=>"2",
                            "card_dealer_id"=>$params["card_dealer_id"],
                            "exchange_start_time"=>strtotime($lifespan[0]),
                            "exchange_end_time"=>strtotime($lifespan[1]),
                        ];
                    }
                    if(!empty($log_update)){
                        $Entitylog->saveAll($log_update);
                    }
                    /********* 修改实体卡记录表 end******************/
                    /********* 生成划拨记录 start******************/
                    $transferlog=[
                        "card_entity_id"=>$row["id"],
                        "transfer_num"=>$params["transfer_num"],
                        "card_dealer_id"=>$params["card_dealer_id"],
                    ];
                    $Transferlog=new \app\common\model\card\Transferlog();
                    $Transferlog->save($transferlog);
                    /********* 生成划拨记录 end******************/
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function table2()
    {
        $this->model = model('AdminLog');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch('index');
    }

}
